package com.zsy.interceptor;

import com.zsy.service.impl.SpringUserDetailsService;
import com.zsy.utils.JwtTokenUtil;
import com.zsy.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    SpringUserDetailsService myUserDetailsService;

    @Resource
    JwtTokenUtil jwtTokenUtil;


    @Override                       //包含客户端请求信息的对象          用于发送响应给客户端的对象       过滤器链中的下一个过滤器
    protected void doFilterInternal(HttpServletRequest request,  HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        log.info("url:"+request.getRequestURI());
        log.info("jwt:"+request.getHeader("Authorization"));

        String jwtToken = request.getHeader(jwtTokenUtil.getHeader());

        System.out.println("jwtToken:"+jwtToken);
        if(!StringUtils.isEmpty(jwtToken)){
            String username = jwtTokenUtil.getUsernameFromToken(jwtToken);
            //如果可以正确的从JWT中提取用户信息，并且该用户未被授权
            if(username != null ){
                UserDetails userDetails = myUserDetailsService.loadUserByUsername(username);
                if(jwtTokenUtil.validateToken(jwtToken,userDetails)){
                    //给使用该JWT令牌的用户进行授权   userDetails.getAuthorities()表示用户拥有的权限角色
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null, userDetails.getAuthorities());
                    //用于将认证信息存入上下文
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }
        filterChain.doFilter(request,response);
    }
}